package com.example.upload.redis;

import com.example.upload.exception.BusinessRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author lsx
 * @description: TODO
 * @date 2024年06月06日 14:54
 * @Version: 1.0
 */
//@Component
//@Slf4j
public class RedisUtils {

//    @Autowired
    private RedissonClient redissonClient;

    public void lockExecution(String key,Runnable runnable){
        RLock lock = null;
        try {
            lock = redissonClient.getLock(key);
            if(ObjectUtils.isEmpty(lock)){
                throw new BusinessRuntimeException("上锁失败，未获取到锁！");
            }
            boolean haveLock = lock.tryLock(60, 60, TimeUnit.SECONDS);
            if (haveLock) {
                runnable.run();
            }else{
                throw new BusinessRuntimeException("执行逻辑失败，加锁失败！");
            }
        } catch (InterruptedException e) {
            BusinessRuntimeException bre = new BusinessRuntimeException("出现异常错误!");
            bre.initCause(e);
            throw bre;
        }
        finally {
            if (!ObjectUtils.isEmpty(lock) && lock.isLocked()) {
                lock.unlock();
            }
        }
    }
}
